import email
import os
from imapclient import IMAPClient
from datetime import datetime, timedelta

username = "wzjahucm@163.com"
password = "AMRmR3BtdwAa9umM"
imap_host = "imap.163.com"

# context manager ensures the session is cleaned up
with IMAPClient(host=imap_host) as client:
    client.login(username, password)

    client.id_({
        'name': 'python-client',
        'vendor': 'XXX',
        'version': '1.0.0',
        'contact': 'XXX@163.com'
    })

    client.select_folder('INBOX')

    one_month_ago = (datetime.now() - timedelta(days=60)).strftime('%d-%b-%Y')
    messages = client.search(['NOT', 'DELETED', 'SINCE', one_month_ago])

    for i, message_id in enumerate(messages):
        print(f"Processing {i + 1}/{len(messages)}")

        response = client.fetch([message_id], ['RFC822'])
        raw_email = response[message_id][b'RFC822']
        msg = email.message_from_bytes(raw_email)

        for part in msg.walk():
            filename = part.get_filename()
            if filename:
                try:
                    decoded = email.header.decode_header(filename)[0]
                    if isinstance(decoded[0], bytes):
                        filename = decoded[0].decode(decoded[1] or 'utf-8')
                    else:
                        filename = decoded[0]
                except:
                    pass

                payload = part.get_payload(decode=True)
                if payload:
                    if not os.path.exists('attachments'):
                        os.makedirs('attachments')

                    filepath = f"attachments/{filename}"

                    if "人工智能" in filename:
                        with open(filepath, 'wb') as f:
                            f.write(payload)

                        print(f"Downloaded: {filename}")
